#include <stdio.h>
#include "scan.h"
#include "selector.h"
#include "sub.h"
#include "opt.h"

static void usage(void)
{
	printf("Usage: %s [selectors] [FILE]\n", prog);
}

static scan_verdict
callback(scan_phase phase, struct tagbuf *b, struct context *ctx)
{
	(void)b;
	if (phase == TAG && !is_selected(ctx))
		return DISCARD;
	return OUTPUT;
}

static int show_help;

static const struct option_def optdef[] = {
	{OPT_FLAG, 0, "help", {.flag = &show_help}, "show help", 0},
	{.type = OPT_GROUP, .ptr = {.group = &selector_options}},
	{.type = OPT_END},
};
static const struct option_group optgroup = {.defs = optdef};

int cut_main(int argc, const char *const *argv)
{
	const char *file = 0;
	int r;
	FILE *in, *out;

	if (parse_options(argc, argv, &optgroup, 1, &file) < 0) {
		usage();
		return 2;
	}
	if (show_help) {
		usage();
		print_options(&optgroup);
		return 0;
	}

	in = open_file(file, 'r');
	if (!in)
		return 1;
	out = open_file(0, 'w');
	if (!out) {
		close_file(in);
		return 1;
	}

	r = scan(in, out, callback);

	close_file(in);
	close_file(out);

	return r;
}
